package com.lbyl.Service;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.lbyl.util.DownLoadBitmapUtil;
import com.lbyl.util.LocalCacheUtil;
import com.lbyl.util.MemoryCacheUtil;

/**
 * @author libin996@outlook.com
 */

public class BitmapService {

    private static final String TAG = "BitmapService";
    private LocalCacheUtil mLocalCacheUtil;
    private MemoryCacheUtil mMemoryCacheUtil;

    public BitmapService(){
        mLocalCacheUtil = new LocalCacheUtil();
        mMemoryCacheUtil = new MemoryCacheUtil();
    }

    /**
     * 图片显示规则:
     * 1.显示默认图片
     * 2.在本地检索图片
     * 3.网络下载图片
     *
     * @param img
     * @param urlStr
     */
    public void display(ImageView img, String urlStr) {
        //1.优先从内存获取图片
        Bitmap bitmap;
        bitmap = mMemoryCacheUtil.getMemoryCache(urlStr);
        if (bitmap != null) {//本地获取成功
            img.setVisibility(View.VISIBLE);
            img.setImageBitmap(bitmap);
            return;
        }

        //2.其次从本地获取图片
         bitmap = mLocalCacheUtil.getLocalCache(urlStr);//尝试从本地获取
        if (bitmap != null) {//本地获取成功
            img.setVisibility(View.VISIBLE);
            img.setImageBitmap(bitmap);
            //2.1写内存缓存
            mMemoryCacheUtil.setMemoryCache(urlStr, bitmap);
            return;
        }
        //2.再次从网络获取
        new BitmapTask().execute(img, urlStr);

    }


    /**
     * 网络下载图片并更新UI
     *
     * @author libin996@outlook.com
     */
    public class BitmapTask extends AsyncTask<Object, Integer, Bitmap> {

        ImageView imageView_image;
        String urlStr;

        @Override
        protected Bitmap doInBackground(Object... params) {
            imageView_image = (ImageView) params[0];
            urlStr = (String) params[1];
            if (urlStr == null) {//直接返回null以设置imageview为gone
                return null;
            }
            return DownLoadBitmapUtil.downLoadBitmapByUrl(urlStr);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            //主线程更新UI

            if (bitmap == null) {//网络返回图片失败,则取消图片
                return;
            }
            //由于线程原因,图片与item不一定对应.此处保证对应
            if (imageView_image.getTag() != urlStr) {
                return;
            }
            imageView_image.setVisibility(View.VISIBLE);
            imageView_image.setImageBitmap(bitmap);//网络图片显示
            imageView_image.invalidate();
            Log.i(TAG, "onPostExecute: 从网络加载图片,网址是"+urlStr);
            //保存本地缓存
            mLocalCacheUtil.setLocalCache(urlStr, bitmap);
            //写本地缓存
            mMemoryCacheUtil.setMemoryCache(urlStr,bitmap);
        }


    }
}
